<template>
  <van-popup
    teleport="body"
    v-model:show="show"
    closeable
    position="right"
    :style="{ height: '100%', width: '100%' }"
  >
    <div class="content_wrapper main_bg">
      <headback
        :title="t('lendUsdt')"
        isGoBack
        :goBack="goBack"
        class="border_bottom"
      ></headback>
      <div class="wrap">
        <div class="lend_des">
          {{ t("lendDes") }}
        </div>
        <div class="form_box">
        <div class="lend_title2">
          {{ t("Iprovide") }}
          <div class="tip">（ {{ t('platGet') }} {{store.state.platformFee*100}} %  {{ t('fee') }}）</div>
        </div>
        <div class="form_item">
          <div class="form_content">
            <van-field type="number" v-model="usdtValue" :placeholder="t('')">
              <template #button> </template>
            </van-field>

            <van-popover v-model:show="showPopover2" placement="bottom-end">
              <div class="language_box">
                <div
                  class="language_item"
                  v-for="item in tokenList"
                  :key="item.contract"
                  :class="{
                    language_item_active: nowToken.contract == item.contract,
                  }"
                  @click="chooseUsdt(item)"
                >
                  <span class="usdt_box">
                    <img :src="requireImg(item.img)" alt="" />
                    {{ item.name }}
                  </span>
                </div>
              </div>
              <template #reference>
                <span class="color_light">
                  <img :src="requireImg(nowToken.img)" alt="" />
                  {{ nowToken.name }}
                  <i class="icon_down iconfont icon-ic_down"></i>
                </span>
              </template>
            </van-popover>
          </div>
        </div>
        <div class="form_line">
          <div class="lend_title">{{  t('way') }}</div>
          :
          <van-radio-group  v-model="loanType" shape="square"  direction="horizontal">
            <van-radio name="0">
              <div class="flex_class">
              {{ t('fixedWay') }}  
              <iconTip title="" placement="top-end">
                <div>固定期限内借贷</div>
                <div>提前三天可还款（利息按全部算）</div>
                <div>超时还款：超时部分按天计算利息</div>
              </iconTip>
            </div>
            </van-radio>
            <van-radio name="1">
              <div class="flex_class">
              {{ t('freeWay') }}
              <iconTip title="" placement="top-end">
                <div>随借随还借贷</div>
                <div>按天计算利息</div>
                <div>随时还款</div>
              </iconTip>
            </div>
            </van-radio>
          </van-radio-group>
        </div>
        
        <div class="form_line">
        <div class="lend_title">
          {{ t("duration") }}
        </div>:
        <van-popover v-model:show="showPopover" placement="bottom-end">
                <div class="language_box">
                  <div
                    class="language_item2"
                    v-for="item in durationOption"
                    :key="item.id"
                    :class="{
                      language_item_active: nowDay.id == item.id,
                    }"
                    @click="chooseTime(item)"
                  >
                    <span class="usdt_box">
                      {{ item.name }}  <span class="days_rate" v-if="item.rate">  {{ item.rate*100 }} %</span>
                    </span>
                  </div>
                </div>
                <template #reference>
                  <div class="form_item">
                  <span class="color_light2 rate_class">
                    {{ nowDay.name }}
                    <i class="icon_down iconfont icon-ic_down"></i>
                  </span>
                </div>
                </template>
              </van-popover>
        <div class="form_item" v-if="durationId==0">
              <div class="form_content">
                <van-field type="digit"  class="rate_class" v-model="customDay" :placeholder="t('')">
              <template #button> </template>
          </van-field>
            <span class="rate_margin">days</span> 
            </div>
            </div>
        </div>
              <!-- 利息 -->
        <div class="form_line">
          <div class="lend_title">
            {{ t("Interest") }}
          </div>:
          <div class="flex_box"> 
            <div class="form_item">
              <div class="form_content">
            <van-field class="rate_class" type="number" v-model="realRate" :placeholder="t('')">
              <template #button>% </template>
            </van-field>
            <span class="rate_margin"> <div>{{dayRate}}</div> <div>{{ interestRate }}</div> </span> 
            </div>
            <iconTip title="" placement="top-end">
              <div>利息金额 = USDT数量 * 利率</div>
              <div>超出还款日期按天计算利息</div>
            </iconTip>
            
            </div>
          </div>
        </div>
        <div class="form_item form_line" style="flex: 1">
            <div class="lend_title">{{ t("shop") }}</div>
            :
            <div class="form_content">
              <van-cell class="tarder_name" @click="setShop" :value="props.shopData.name||shopName" :is-link="!props.shopData.name" />
            </div>
          </div>
        <!-- 小费 -->
        <div class="form_line">
          <div class="lend_title">
            {{ t("ConfirmationTip") }}
          </div>:
          <div class="flex_box"> 
            <div class="form_item">
              <div class="form_content">
            <van-field class="rate_class" type="number" v-model="tipRate" :placeholder="t('')">
              <template #button>% </template>
            </van-field>
            <span class="rate_margin">
              <div class="interest_amount">
                  <span>{{ tipValue }}</span> 
                  <img
                    class="token_img"
                    :src="requireImg(nowToken.img)"
                    alt=""
                  />
                  {{ nowToken.name }}
                </div>
            </span> 
            <iconTip title="" placement="top-end">
                <div>小费给到交易员</div>
                <div>如果没有选择交易员</div>
                <div>则给到平台</div>
              </iconTip>
            </div>
            </div>
          </div>
        </div>
  
        <div class="form_line">
          <div class="lend_title">
            {{ t("interestAmount") }}
            <!-- 利息金额 -->
          </div>:
          <div class="interest_amount">
            {{t('aboutGet')}}
            <img class="token_img" :src="requireImg(nowToken.img)" alt="" />
            {{ interestAmount }} {{ nowToken.name }}
          </div>
        </div>
 
      
        <div class="form_line">
          <div class="lend_title">
            {{ t("是否可平仓") }}
            <!-- 利息金额 -->
          </div>:
          <div class="interest_amount">
            {{ store.state.myUserObj.isCloseOut ? '可平仓' :'不可平仓'}} 
          </div>
          <div @click="goToPage('user')" class="can_click">修改</div>
          <iconTip title="" placement="top">
                <div>是否平仓由您配置决定</div>
                <div>可平仓，就是价格下跌20%后，</div>
                <div> 您可以执行平仓操作，</div>
                <div>获取借入人质押的vds。</div>
              </iconTip>
        </div>
        <div class="form_line">
          <div class="lend_title">
            {{ t("remark") }}
          </div>:
          <div class="flex_box" style="width: 100%;"> 
            <div class="form_item">
              <div class="form_content textArea_field">
            <van-field  type="textarea" rows="1"  v-model="formData.remark" :placeholder="t('')">
            </van-field>
            </div>
            </div>
          </div>
        </div>
      </div>
      </div>
      <div class="fixedD">
        <div class="needPay">
          <span>{{t('aboutLend')}} ：</span>
          <span class="payU"> {{ needPay }} {{ store.state.USDT}}</span>
          <iconTip title="" placement="top">
                <div>数量： {{ usdtValue }} {{ store.state.USDT}}</div>
                <div>服务费 ： {{ feeValue }} {{ store.state.USDT}}</div>
                <div>小费： {{tipValue  }}{{ store.state.USDT}} </div>
              </iconTip>
        </div>
        {{ t('myValue') }} ： {{ store.state.usdtBalance }} {{ store.state.USDT}}
        
      </div>
      <div class="fixedbutton background_box">
        <van-button :loading="loading" @click="confirm" type="primary">
          <div>{{ t("toOrder") }}</div>
        </van-button>
      </div>
    </div>
  </van-popup>
  <shopChoose
    v-model="showShop"
    v-model:checkedValue="shopId"
    @change="shopChange"
    @clear="clearShop"
  ></shopChoose>
</template>
<script setup>
import AESUtils from "@/utils/AES.js";
import { showToast } from "vant";
import "vant/es/toast/style";
import { ethers } from "ethers";
import { useStore } from "vuex";
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useI18n } from "vue-i18n";
const { locale, t } = useI18n();
import { usdtContract, usdcContract, loanContract } from "@/utils/config.js";
const store = useStore();
import { useRouter } from "vue-router";
import { upload, jsonUpload, IPFS_PUBLIC_URL, getJson } from "@/api/User.js";
import loanEth from "@/utils/loanEth.js";
import eth from "@/utils/eth.js";
const requireImg = (imgPath) => {
  return new URL(`../assets/images/${imgPath}`, import.meta.url).href;
};
const showPopover2 = ref(false);
const loanType = ref('0')
const usdtValue = ref(10);
const router = useRouter();
const loading = ref(false);
const headTitle = ref(t("addUser"));
const durationId = ref(7);
const customDay = ref(7)
const showShop = ref(false);
const shopName = ref("");
const tipRate = ref(0)
const shopId = ref("");
const setShop = () => {
  if(props.shopData.name){

  }else{
    showShop.value = true;
  }
};
const nowShop = ref({})
const clearShop = (item) => {
  shopId.value = '',
  shopName.value = '';
  nowShop.value = {}
};
const shopChange = (item) => {
  shopId.value = item.account;
  shopName.value = item.name;
  nowShop.value = item
  tipRate.value = item.tipRate*10000/100
};
const tokenList = [
  {
    contract: usdtContract[0],
    name: usdtContract[1],
    decimal: usdcContract[3],
    img: usdtContract[4],
  },
  // {
  //   contract: usdcContract[0],
  //   name: usdcContract[1],
  //   decimal: usdcContract[3],
  //   img: usdcContract[4],
  // },
];
const nowToken = ref(tokenList[0]);

const interestRate = computed(() => {
  return  ((durationId.value || Number(customDay.value) ) &&realRate.value) ? '(' +  t('yearRate') +  parseFloat((365/    (durationId.value || customDay.value)   * realRate.value).toFixed(2) )  + ' % )': '';
});
const dayRate  = computed(() => {
  return  ((durationId.value || Number(customDay.value) ) &&realRate.value) ? '(' + t('dayRate')  + parseFloat((realRate.value/ (durationId.value || customDay.value)).toFixed(3) )  + ' % )': '';
});
const realRate = ref(1)
// watch(durationId,(n,o)=>{
//   let obj = {
//     7: "1",
//     15: "1.21",
//     30: "1.46",
//     60: "2.14",
//     90: "3.12",
//     0:'0',
//   };
//   realRate.value = Number(obj[durationId.value])
// })
// 小费
const tipValue = computed(()=>{
  return  parseFloat(((tipRate.value/100) * usdtValue.value).toFixed(6))
})
// 手续费
const feeValue = computed(()=>{
  return  parseFloat(((store.state.platformFee) * usdtValue.value).toFixed(6))
})
const needPay = computed(()=>{
  return parseFloat((Number(usdtValue.value) + tipValue.value + feeValue.value).toFixed(2))
})
const interestAmount = computed(() => {
  return parseFloat((usdtValue.value * realRate.value/100).toFixed(6));
});
const chooseUsdt = (value) => {
  nowToken.value = value;
  showPopover2.value = false;
};

const showPopover = ref(false)
const nowDay = ref({})
const chooseTime = (item) =>{
  nowDay.value = item
  durationId.value = item.day
  realRate.value = item.rate*100
  showPopover.value = false
}
const durationOption = computed(()=>{
  if(loanType.value==0){
    let arr = store.state.fixedTime.filter(res=>res.isActive)
    let arr2 = [{name:'自定义',day:0,rate:0}]
    return [...arr,...arr2]
  }else{
    let arr = store.state.freeTime.filter(res=>res.isActive)
    let arr2 = [{name:'自定义',day:0,rate:0}]
    return [...arr,...arr2]
  }
})
watch(
  () => durationOption.value,
  (newValue) => {
    if (newValue) {
      if(newValue&&newValue.length>0){
        chooseTime(newValue[0])
      }
    }
  },{
    immediate:true
  }
);
// const durationOption = ref([
//   { text: "7 days", value: 7 },
//   { text: "15 days", value: 15 },
//   { text: "30 days", value: 30 },
//   { text: "60 days", value: 60 },
//   { text: "90 days", value: 90 },
//   { text: "自定义", value: 0 },
// ]);
const props = defineProps({
  shopData:{
    type:Object,
    default:()=>{
      return {}
    }
  },
  modelValue: {
    type: Boolean,
    default: false,
  },
  orderType: {
    type: [String, Number],
    default: "1",
  },
});
shopName.value = props.shopData.name
watch(
    () => props.shopData,
    (newProps) => {
      if(newProps&&newProps.name){
        shopChange(newProps)
      }
    }
);
watch(
    () => store.state.myUserObj,
    (newProps) => {
      if(newProps&&newProps.trader){
          let item = store.state.shopList.find(res=>res.account==newProps.trader)
          if(item){
            shopChange(item)
          }
      }
        // childList.value = newProps.listData
    },{
      immediate:true
    }
);
const emit = defineEmits(["change", "update:modelValue", "close"]);
let show = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});
watch(
  () => show.value,
  (newValue) => {
    if (newValue) {
      main();
    }
  }
);
const goBack = () => {
  show.value = false;
};
let formData = ref({
  id: "1",
  price: "",
  remark: "",
});
const main = async () => {
  tipRate.value = store.state.minFee*100
  formData.value = {
    id: "1",
    price: "",
    remark: "",
  };
};
main();
const goToPage = (value) => {
  router.push({
    name: value,
  });
};
const confirm = async () => {
  if (!usdtValue.value) {
    showToast(t("pleseAmount"));
    return;
  }
  if (usdtValue.value < 10) {
    showToast(t("minAmount"));
    return;
  }
  if(tipRate.value < store.state.minFee*100){
    showToast("小费不能低于" + (store.state.minFee*10000/100) + '%')
    return
  }
  if(tipRate.value < nowShop.value.tipRate*100){
    showToast("小费不能低于" + (nowShop.value.tipRate*10000/100) + '%')
    return
  }
  if(nowDay.value.day){
    if(Number(realRate.value) < (nowDay.value.rate*100)){
      showToast("利息不能少于" + (nowDay.value.rate *100) + '%')
      return
    }
  }else{
    if(Number(realRate.value)<=0){
      showToast("请填写利息")
    }
  }
  let tokenValue = await eth.getBalanceOf(
    nowToken.value.contract,
    nowToken.value.decimal
  );
  let needPayU = parseFloat(((Number(usdtValue.value) + Number(tipValue.value) +   Number(feeValue.value)) * 1.1).toFixed(6));
  if (tokenValue < needPayU )  {
    showToast(t("noMoney"));
    return;
  }
  loading.value = true;
  try {
    let allowance = await eth.getAllowance(
      nowToken.value.contract,
      loanContract,
      nowToken.value.decimal
    );
    if (needPayU > Number(allowance)) {
      await eth.approve(
        needPayU,
        nowToken.value.contract,
        loanContract,
        nowToken.value.decimal
      );
      // 授权
    }
    let amount = ethers.utils.parseUnits(
      String(usdtValue.value),
      nowToken.value.decimal
    );
    let hex = await loanEth.ContractWithSinger.createOrder(
      amount,
      2,
      durationId.value || customDay.value,
      (realRate.value/100*10000).toFixed(0),
      (tipRate.value/100*10000).toFixed(0),
      shopId.value || "0x0000000000000000000000000000000000000000",
      loanType.value,
      store.state.myUserObj.isCloseOut?true:false,
      formData.value.remark,
    );
    await hex.wait();
    loading.value = false;
    showToast(t("orderSuccess"));
    goBack()
    goToPage("myOrder");
  } catch (err) {
    showToast(t("orderFail"));
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
// .fixedD{
//   position: fixed;
//   bottom: calc(env(safe-area-inset-bottom) + 50px);
// }
// .fixedbutton {
//   width: 100%;
//   position: fixed;
//   display: flex;
//   height: 55px;
//   align-items: center;
//   justify-content: center;
//   bottom: calc(env(safe-area-inset-bottom));
// }
.form_box{
  border: 1px solid #888;
  margin-top: 8px;
  padding: 2px 6px 12px 6px;
  border-radius: 8px;
}
.flex_class{
  display: flex;
  align-items: center;
  // font-size: 10px;
}
.tip{
  color: #f77a2f;
}
.tip2{
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 6px;
  .num_value{
    font-size: 14px;
    font-weight: bold;
    color: #f77a2f;
  }
}
:deep .van-cell__right-icon {
  display: flex;
  align-items: center;
}
.rate_margin{
  margin-left: 10px;
  display: flex;
  align-items: center;
  flex-direction: column;
}
.form_line {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 10px;
  min-height: 32px;
  // font-size: 11px;
}
.language_box {
  padding: 5px 0px;
  background: #222143;
}
.menu_box {
  min-width: 148px;
  max-height: 75vh;
  overflow: auto;
  background-color: #222143;
  border-radius: 8px;
  padding: 8px;
  box-shadow: rgba(0, 0, 0, 0.25) 0 4px 12px;
  font-size: 14px;
  z-index: 100;
}
.days_rate{
  margin-left: 10px;
  color: #999;
}
.menu_item {
  display: flex;
  padding: 8px;
  color: inherit;
  text-decoration: none;
  font-weight: 400;
}
:deep .van-popover__wrapper{
  flex-shrink: 0;
}
.color_light2 {
  box-sizing: border-box;
  color: #ddd;
  display: inline-block;
  border: 1px solid #414c60;
  padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);
  height: 1.2rem;
  // margin-left: 10px;
  
  border-radius: 5px;
  flex-shrink: 0;
  min-width: auto;
  display: flex;
  align-items: center;
  .icon_down {
    font-size: 10px;
    margin-left: 4px;
  }
  img {
    height: 16px;
    margin-right: 7px;
  }
}
.color_light {
  color: #ddd;
  display: inline-block;
  border: 1px solid #414c60;
  padding: var(--van-cell-vertical-padding) 6px;
  margin-left: 10px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  .icon_down {
    font-size: 10px;
    margin-left: 4px;
  }
  img {
    height: 16px;
    margin-right: 7px;
  }
}
.usdt_box {
  color: #ddd;
  display: inline-block;
  border-radius: 5px;
  display: flex;
  align-items: center;
  img {
    height: 16px;
    margin-right: 7px;
  }
}
.language_item {
  font-size: 12px;
  padding: 10px 15px;
  cursor: pointer;
  text-align: center;
  display: flex;
  align-items: center;

  .van-image {
    height: 18px;
    width: 18px;
    margin-right: 8px;
  }
}
.language_item2 {
  font-size: 12px;
  padding: 6px 15px;
  cursor: pointer;
  text-align: center;
  display: flex;
  align-items: center;
}
.confirm_notice {
  font-size: 10px;
  color: #333;
}
.drop_item {
  padding: 10px 10px;
  display: flex;
  align-items: center;
  gap: 8px;
  .drop_num {
    width: 20px;
    text-align: right;
  }
}
.drop_active {
  color: #f77a2f;
}
.interest_amount {
  display: flex;
  align-items: center;
  gap: 6px;
}
// .van-dropdown-menu{
//    border: 1px solid #414c60;
//   border-radius: 8px;

// }
:deep .van-dropdown-menu__title {
  font-size: 12px;
}
:deep .van-dropdown-menu__bar {
  border: 1px solid #414c60;
  border-radius: 6px;
  height: 36px;
  display: inline-flex;
  padding-right: 10px;
  font-size: 10px;
}


.lend_title {
  font-weight: bold;
  min-width: 55px;
  text-align-last: justify;
  // font-size: 10px;
}
.lend_title2 {
  font-weight: bold;
  display: flex;
  align-items: center;
  min-width: 55px;
  margin: 10px 0;
  // font-size: 10px;
  gap: 6px;
}
.van-cell {
  font-size: 12px;
  background: transparent !important;
}
.content_wrapper {
  height: calc(100vh - 10px);
  box-sizing: border-box;
  overflow: auto;
  background: #eff0f4;
}
.isHeight {
  height: 100vh;
}
.wrap {
  padding: 10px 12px 20px 12px;
  // min-height: calc(100vh - 150px);
  // overflow: auto;
  margin-top: 40px;
  position: relative;
  .lend_des {
    display: flex;
    line-height: 2em;
    // font-size: 10px;
  }
  .van-button {
    margin-top: 0.58667rem;
    width: 100%;
    height: 1.06667rem;
    font-size: 0.48rem;
    font-weight: 500;
    border-radius: 0.53333rem;
  }

  .van-button--primary {
    border: none;
    font-size: 0.48rem;
    font-weight: 400;
  }

  :deep .van-cell__right-icon {
    font-size: 12px;
  }
  .picture_tips {
    color: #999;
  }

  .form_item {
    display: flex;
    padding: 0;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .form_title {
      display: flex;
      align-items: center;
      opacity: 0.8;
      // font-size: 11px;
    }

    .line_h30 {
      line-height: 30px;
    }
    .rate_class{
      width: 80px;
    }
    .form_content {
      flex: 1;
      display: flex;
      align-items: center;
      .van-field {
        border: 1px solid #414c60;
      }

      .radio_group {
        padding: 0.31rem 0.5rem;
      }
      .van-cell {
        font-size: 11px;
      }
      // display: flex;
      // justify-content: flex-end;
    }
  }
}
</style>
